import './style.css'
import * as THREE from "three";
import { PCDLoader } from 'three/examples/jsm/loaders/PCDLoader'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';

import { GUI } from 'three/examples/jsm/libs/lil-gui.module.min.js';

let camera, scene, renderer;
let loadedPoints; // 新增变量用于存储加载的点云对象

init();
render();

function init() {

  renderer = new THREE.WebGLRenderer({ antialias: true });
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

  scene = new THREE.Scene();

  camera = new THREE.PerspectiveCamera(30, window.innerWidth / window.innerHeight, 0.01, 40);
  camera.position.set(0, 0, 1);
  scene.add(camera);

  const controls = new OrbitControls(camera, renderer.domElement);
  controls.addEventListener('change', render); // use if there is no animation loop
  controls.minDistance = 0.2;
  controls.maxDistance = 10;

  const loader = new PCDLoader();
  loader.load('/Zaghetto.pcd', function (loadedPointsInstance) { // 修改回调函数参数名称

    loadedPointsInstance.geometry.center();
    loadedPointsInstance.geometry.rotateX(Math.PI);
    loadedPointsInstance.name = 'Zaghetto.pcd';
    scene.add(loadedPointsInstance);

    // 添加颜色属性
    const numPoints = loadedPointsInstance.geometry.attributes.position.count;
    const colors = new Float32Array(numPoints * 3); // 创建颜色数组，每个点占用3个浮点数（RGB）

    for (let i = 0; i < numPoints; i++) {
      // 为每个点生成随机颜色
      // const color = new THREE.Color().setHSL(Math.random(), 1, 0.5);
      const color = new THREE.Color('#00FFFF');
      colors[i * 3] = color.r;
      colors[i * 3 + 1] = color.g;
      colors[i * 3 + 2] = color.b;
    }

    loadedPointsInstance.geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3)); // 添加颜色属性到geometry

    const material = new THREE.PointsMaterial({
      size: 0.002,
      vertexColors: true, // 启用顶点颜色映射
    });
    
    loadedPointsInstance.material = material;

    loadedPoints = loadedPointsInstance;

    const gui = new GUI();

    gui.add(loadedPoints.material, 'size', 0.001, 0.01).onChange(render);
    gui.addColor(loadedPoints.material, 'color').onChange(render);
    gui.open();

    // 添加点击事件监听器，并绑定到onCanvasClick函数
    renderer.domElement.addEventListener('mousedown', function (event) { // 包裹一层匿名函数以便传递loadedPoints
      onCanvasClick(event, loadedPoints);
    });

    render();
  });

  window.addEventListener('resize', onWindowResize);
}

// function onCanvasClick1(event,pointCloud) {
//   event.preventDefault();

//   const mouseScreenCoords = {
//     x: event.clientX,
//     y: event.clientY,
//   };

//   const mouseNormalizedCoords = {
//     x: (event.clientX / renderer.domElement.clientWidth) * 2 - 1,
//     y: -(event.clientY / renderer.domElement.clientHeight) * 2 + 1,
//   };

//   const mouseWorldCoords = unproject(mouseNormalizedCoords, camera);

//   const rayOrigin = camera.position;
//   const rayDirection = mouseWorldCoords.clone().sub(rayOrigin).normalize();

//   let closestPoint = null;
//   let closestDistance = Infinity;
//   const positionAttribute = pointCloud.geometry.attributes.position;

//   for (let i = 0; i < positionAttribute.count; i++) {
//     const vertexPosition = new THREE.Vector3(
//       positionAttribute.getX(i),
//       positionAttribute.getY(i),
//       positionAttribute.getZ(i)
//     );

//     const distance = rayOrigin.distanceToSquared(vertexPosition);

//     if (distance < closestDistance) {
//       closestDistance = distance;
//       closestPoint = vertexPosition.clone();
//     }
//   }

// }

// function unproject(screenCoords, camera) {
//   const vector = new THREE.Vector3(
//     screenCoords.x,
//     screenCoords.y,
//     0.5
//   );
//   vector.unproject(camera);
//   return vector;
// }

function onCanvasClick(event, points) { // 添加points参数
  event.preventDefault();

  const mouse = new THREE.Vector2();
  mouse.x = (event.clientX / renderer.domElement.clientWidth) * 2 - 1;
  mouse.y = -(event.clientY / renderer.domElement.clientHeight) * 2 + 1;

  const raycaster = new THREE.Raycaster();
  raycaster.setFromCamera(mouse, camera);
  // raycaster.params.Points.threshold = 0; // 设置阈值为0，禁用快速近似算法

  const intersections = raycaster.intersectObject(points, /* recursive = */ true);

  if (intersections.length > 0) {
    console.log(intersections.length);
    const closestIntersection = intersections[0];

    // 获取被点击点在顶点数组中的索引
    const index = closestIntersection.index;
    console.log(index)

    // 获取点云的顶点颜色数组
    const colors = points.geometry.getAttribute('color').array;

    // 变换被点击点的颜色
    colors[index * 3] = 255; // 红色分量
    colors[index * 3 + 1] = 0; // 绿色分量
    colors[index * 3 + 2] = 0; // 蓝色分量

    // 更新点云材质
    points.geometry.attributes.color.needsUpdate = true;

    render();
  }
}

function onWindowResize() {

  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize(window.innerWidth, window.innerHeight);

  render();

}

function render() {

  renderer.render(scene, camera);

}



// const container = document.createElement('div');
// document.body.appendChild(container);

// //创建场景和相机
// const scene = new THREE.Scene();
// const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
// const renderer = new THREE.WebGLRenderer({ antialias: true });
// renderer.setSize(window.innerWidth, window.innerHeight);
// container.appendChild(renderer.domElement);

// //加载点云
// const loader = new PCDLoader();
// loader.load('/Zaghetto.pcd', pointCloud => {
//   scene.add(pointCloud);
//   render();
// }, undefined, error => console.error('Failed to load PCD file:', error));


// const controls = new OrbitControls(camera, renderer.domElement);
// controls.enableZoom = true;


// camera.position.z = 5;

// function render() {
//   requestAnimationFrame(render);
//   renderer.render(scene, camera);
// }
// function onWindowResize() {
//   camera.aspect = window.innerWidth / window.innerHeight;
//   camera.updateProjectionMatrix();
//   renderer.setSize(window.innerWidth, window.innerHeight);
// }
// window.addEventListener('resize', onWindowResize);





// const scene = new THREE.Scene();
// const camera = new THREE.PerspectiveCamera(
//     45, //视角 视角越大  能看到的范围就越大
//     window.innerWidth / window.innerHeight,//相机的宽高比  一般和画布一样大最好
//     0.1,  //近平面  相机能看到最近的距离
//     1000  //远平面  相机能看到最远的距离
// );

// const renderer = new THREE.WebGLRenderer(0);
// renderer.setSize(window.innerWidth, window.innerHeight);
// document.body.appendChild(renderer.domElement);

// const loader = new PCDLoader();

// loader.load(
// 	'/Zaghetto.pcd',
// 	function ( points ) {
// 		scene.add( points );
// 	},
// 	function ( xhr ) {
// 		console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
// 	},
// 	function ( error ) {
// 		console.log( 'An error happened:'+error );
// 	}
// );


//demo1
// //创建场景
// const scene = new THREE.Scene();

// //创建相机
// const camera = new THREE.PerspectiveCamera(
//     45, //视角 视角越大  能看到的范围就越大
//     window.innerWidth / window.innerHeight,//相机的宽高比  一般和画布一样大最好
//     0.1,  //近平面  相机能看到最近的距离
//     1000  //远平面  相机能看到最远的距离
// );

// //c创建一个canvas容器  并追加到 body上
// const renderer = new THREE.WebGLRenderer(0);
// renderer.setSize(window.innerWidth, window.innerHeight);
// document.body.appendChild(renderer.domElement);

// //创建一个几何体
// const geometry = new THREE.BoxGeometry(1, 1, 1);
// //创建材质
// const material = new THREE.MeshBasicMaterial({ color:0x08ffe });
// //创建网格
// const cube = new THREE.Mesh(geometry, material);
// //将网格添加到场景中
// scene.add(cube);
// //设置相机位置   这里 我们设置Z轴  大家可以试试  S Y 和 Z  都是可以的
// camera.position.z = 5;
// //设置相机默认看向哪里   三个 0  代表 默认看向原点
// camera.lookAt(0, 0, 0);
// //将内容渲染到元素上
// renderer.render(scene, camera);



// function animate() {
//   requestAnimationFrame(animate);
//   cube.rotation.x += 0.01;
//   cube.rotation.y += 0.01;
//   renderer.render(scene, camera);
// }
// animate();








// import javascriptLogo from './javascript.svg'
// import viteLogo from '/vite.svg'
// import { setupCounter } from './counter.js'

// document.querySelector('#app').innerHTML = `
//   <div>
//     <a href="https://vitejs.dev" target="_blank">
//       <img src="${viteLogo}" class="logo" alt="Vite logo" />
//     </a>
//     <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript" target="_blank">
//       <img src="${javascriptLogo}" class="logo vanilla" alt="JavaScript logo" />
//     </a>
//     <h1>Hello Vite!</h1>
//     <div class="card">
//       <button id="counter" type="button"></button>
//     </div>
//     <p class="read-the-docs">
//       Click on the Vite logo to learn more
//     </p>
//   </div>
// `

// setupCounter(document.querySelector('#counter'))
